// pages/my_shop_list/my_shop_list.js
const app = getApp();
const $get_api = require('../../common/api').HTTP;
let heightArr = [0]  // 存放高度累加数组
const wx_auth = require('../../common/wx_auth') //微信授权js
const util = require('../../utils/util')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        wx_auth:wx_auth.authApply,
        util:util,
        rightId: 'right0',
        leftView: 0,
        select_type: 0, // page：当前页--
        l_page: 0,
        no_more: false, 
        isLoading: true, 
        list_page: 1, 
        limit:10,
        last_page:1,
        menuArr:{
            "class":[
                {id:0,name:"全部"},
            ],
            "tags":[
                { num: 0,bgColor:'transparent',bgColor_h:'#435c4e',txtColor:'#000',txtColor_h:"#fff",title:"推荐"}, 
                { num: 1,bgColor:'transparent',bgColor_h:'#435c4e',txtColor:'#000',txtColor_h:"#fff",title:"销量"},
                { num: 2,bgColor:'transparent',bgColor_h:'#435c4e',txtColor:'#000',txtColor_h:"#fff",title:"上新"}
            ],
            "shops":[],
        },
        nomore:app.imgUrl + "no_more.png"+ app.version,
        p_id:0,//左侧导航类型
        class_id:null,//左侧默认id
        keyword:'',// 搜索框内容，使用的是简易的双向绑定 //温习一下：第一层才能进行双向绑定
        keywords:[],//历史搜索的数组
        label_img:app.imgUrl + "my_qiye/label_img.png"+ app.version,
        right_icon:app.imgUrl + "youjiantou.png"+ app.version,
        img:app.imgUrl + "conpany_search/company_icon.png"+ app.version,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options,"options");
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        const query = wx.createSelectorQuery()
        query.selectAll('.goods').boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec(function (res) {
        res[0].top // #the-id节点的上边界坐标
        res[1].scrollTop // 显示区域的竖直滚动位置
        res[0].map( val => {
            let result = val.height  + heightArr[heightArr.length - 1]
            // console.log(result)
            // 拿后一个view盒子的高度加上前面的高度
            heightArr.push(result) 
        })
        // console.log(heightArr)
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow(options) {
        let that = this;
        console.log(wx.getStorageSync('token'),"token");
        that.data.login_status = wx_auth.checkToken()
        if(!that.data.login_status){
            wx_auth.authApply(options,'');
        }
        if(wx_auth.checkToken(1)){
          that.data.isLoginBtn = false;
          that.navShow();
          // 12313
          that.getLeftType();
          if(that.data.class_id == "" || that.data.class_id == undefined){
              that.data.class_id = 0;
          }
          that.getShopList(1,that.data.limit,0);
      }
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        let _this = this;
        // 构建页面参数
        let params = app.getShareUrlParams({});  //app.js分享为封装
        return {
            title: app.useConst.SET_INFO.share_obj.title,
            //   path: "/pages/order_list/order_list?" + params,
            path: "/pages/index/index?" + params,
            imageUrl: app.useConst.SET_INFO.share_obj.imageUrl
        };
    },
    navShow:function(){
      //控制导航栏出现
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
            selected: 2
        })
    }
  },
    /**
   * 左侧菜单点击事件,事件对象e传输index
   */
  leftMenuClick(e){
    let that = this;
    let uIndex = e.currentTarget.dataset.current_index;
    that.data.class_id = uIndex;
    that.getShopList(1,that.data.limit,that.data.class_id);
    this.setData({
        leftView: uIndex,
        // rightId: 'right' + e.currentTarget.dataset.current_index
      })
  },

  /**
   * 右侧滚动事件
   */
  rightScroll(e) {
    let st = e.detail.scrollTop
    // console.log('st' + e.detail.scrollTop)
    for(let i = 0; i < heightArr.length; i++){
      if(st >= heightArr[i] && st <= heightArr[i+1] - 5){
        this.setData({
          leftView: i,
        })
        // console.log(this.data.leftView)
        return
      }
    }
  },
  getLeftType:function(pid){
    let that = this;
    $get_api.getEnterpriseCate({ 
        a:1
    }).then(r => { 
        let data = r.data.data;
        console.log(data,"获取左侧分类成功");
        that.data.menuArr.class = [];
        that.data.menuArr.class = data.list;
        // that.data.class_id = data[0].id;
        that.setData({
            'menuArr.class':that.data.menuArr.class
        })
    })
  },
  getShopList:function(page = 1,limit = 20, cate_id){
    let that = this;
    that.data.list_page = page
    $get_api.getEnterpriseLits({ 
        page:page,
        limit:limit,
        cate_id:cate_id
    }).then(r => { 
        let data = r.data.data;
        console.log(data,"获取右侧分类成功");
        that.data.menuArr.shops = [];
        that.data.menuArr.shops = data.list;
        console.log(that.data.menuArr.shops,"that.data.menuArr.shops");
        that.data.last_page = Math.ceil(data.count / that.data.limit);
        that.setData({
            'menuArr.shops':that.data.menuArr.shops,
        })
    })
  },
  //下拉刷新
  getGoodsList(isPage, list_page, limit = 20 ) {
    let _this = this;
    $get_api.getEnterpriseLits({ 
        page: list_page || 1,
        limit:limit
    }).then(r => { 
        let resList = r.data.data;
        let dataList = _this.data.menuArr.shops;
        let arr = resList.list;
        console.log(resList,"arr");
        if (isPage == true) {
        _this.setData({
            'menuArr.shops': dataList.concat(arr),
            isLoading: false,
        });
        console.log(_this.data.menuArr.shops,"menuArr.shops");
        } else {
        _this.setData({
            'menuArr.shops': resList.list,
            isLoading: false,
            
        });
        }
        if (_this.data.list_page >= _this.data.last_page) {
        this.setData({
            no_more: true
        });
        }
    })
  },
  bindDownLoad() {
    let that = this;
    if (that.data.list_page >= that.data.last_page) {
      that.setData({
        no_more: true
      });
      return false;
    }
    this.getGoodsList(true, ++that.data.list_page,that.data.limit);
  },

  goto_search_page(e){
    //传类型 keywords传 ""
    let u_type = e.currentTarget.dataset.upage;
    let u_title = e.currentTarget.dataset.title;

    // console.log(u_type,"u_type");
    let new_keyword = ""
    if(u_type != 0){
      wx.navigateTo({
        url: '../company_search/company_search?cate_id='+ u_type +'&keyword=' + new_keyword + '&data_title='+u_title,
      })
    }else{
      return false
    }
  },
   //点击搜索按钮
   onSearch(){
    // this.data.keyword获取数据，
    //trim去除字符串前后多余空格
    const keyword=this.data.keyword.trim()
    //非空判断
    if(keyword==='')
    {
        return wx.showToast({
          icon:'none',
          title: '请输入搜索内容',
        })
      
    }
    //在数组增加内容
    //push是增加在后面，unshift是在前面，历史记录当然是新的在前面
    //这个不会自动更新视图而微信小程序没用提供手动更新视图的api所以不用这个方法
    /* 
    this.data.keywords.unshift(keyword)
    */
   
   //增加数组长度的步骤也可以使用展开运算符
   const arr=[keyword,...this.data.keywords]

    this.setData({
        //先转化为set去重
        //然后重新转化为数组
        keywords:Array.from(new Set(arr)),
        //搜索完成清空搜索框
        keyword:''
    })
    wx.navigateTo({
      url: '../company_search/company_search?cate_id='+0+'&keyword='+keyword+'&data_title=全部',
    })
    // console.log(this.data.keywords)
},
//清空历史记录
onClear(){
  //清空历史记录数组
  this.setData({
      keywords:[]
  })
},

  goto_xiangqing_page:function(e){
    let id = e.currentTarget.dataset.upage;
    let title = e.currentTarget.dataset.title;
    wx.navigateTo({
      url: '../company_introduce/company_introduce?id='+id+'&title='+title,
    })
  }
})